package com.mzj.saas.mservice.pay.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.Constant;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.enums.*;
import com.mzj.saas.commons.util.DataUtils;
import com.mzj.saas.mservice.backlog.entity.*;
import com.mzj.saas.mservice.backlog.repository.*;
import com.mzj.saas.mservice.backlog.vo.BacklogItemRedisVo;
import com.mzj.saas.mservice.bill.entity.*;
import com.mzj.saas.mservice.bill.repository.*;
import com.mzj.saas.mservice.bill.vo.PaymentBillRedisVo;
import com.mzj.saas.mservice.contract.entity.Contract;
import com.mzj.saas.mservice.contract.repository.ContractRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.lock.Repository.SmartLockRepository;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.pay.entity.EstateZfbPay;
import com.mzj.saas.mservice.pay.entity.SaasHouseZfbPay;
import com.mzj.saas.mservice.pay.entity.SaasRepairsZfbPay;
import com.mzj.saas.mservice.pay.repository.EstateZfbPayRepository;
import com.mzj.saas.mservice.pay.repository.SaasHouseZfbPayRepository;
import com.mzj.saas.mservice.pay.repository.SaasRepairsZfbPayRepository;
import com.mzj.saas.mservice.pay.vo.PaymentVo;
import com.mzj.saas.mservice.property.common.RepairsStatusEnum;
import com.mzj.saas.mservice.property.entity.*;
import com.mzj.saas.mservice.property.repository.*;
import com.mzj.saas.mservice.property.vo.RepairsPaymentRedisVo;
import com.mzj.saas.mservice.propertybill.entity.SaasBacklogItemBill;
import com.mzj.saas.mservice.propertybill.repository.SaasBacklogItemBillRepository;
import com.mzj.saas.mservice.propertybill.service.WithDrawService;
import com.mzj.saas.mservice.smartlock.service.ruanku.SmartLockCallBackService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.wallet.entity.Wallet;
import com.mzj.saas.mservice.wallet.entity.WalletBuffer;
import com.mzj.saas.mservice.wallet.repository.WalletBufferRepository;
import com.mzj.saas.mservice.wallet.repository.WalletRepository;
import com.mzj.saas.redis.RedisService;
import com.mzj.saas.sdk.pay.callback.AliPayCallback;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 支付宝
 *
 * @author hp
 */
@Service
public class AliPayService {

    private Logger LOG = LoggerFactory.getLogger(AliPayService.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private HousePaymentOrderRepository housePaymentOrderRepository;
    @Autowired
    private RentBillRepository rentBillRepository;
    @Autowired
    private ExpenseBillRepository expenseBillRepository;
    @Autowired
    private SaasHouseZfbPayRepository saasHouseZfbPayRepository;
    @Autowired
    private EstateZfbPayRepository estateZfbPayRepository;
    @Autowired
    private HousePaymentOrderRelationRepository housePaymentOrderRelationRepository;
    @Autowired
    private EstatePaymentOrderRelationRepository estatePaymentOrderRelationRepository;
    @Autowired
    private EstateExpenseBillRepository estateExpenseBillRepository;
    @Autowired
    private EstatePaymentOrderRepository estatePaymentOrderRepository;
    @Autowired
    private WalletRepository walletRepository;
    @Autowired
    private WalletBufferRepository walletBufferRepository;
    @Autowired
    private RentBillRelationRepository rentBillRelationRepository;
    @Autowired
    private EstateRentBillRepository estateRentBillRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private EstateRepairsRecordRepository estateRepairsRecordRepository;
    @Autowired
    private RepairsPaymentOrderRepository repairsPaymentOrderRepository;
    @Autowired
    private SaasRepairsZfbPayRepository saasRepairsZfbPayRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private SmartLockCallBackService smartLockCallBackService;
    @Autowired
    private BacklogItemLockRepository backlogItemLockRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private BacklogItemContractBillRepository backlogItemContractBillRepository;
    @Autowired
    private BacklogItemRecordSubmitRepository backlogItemRecordSubmitRepository;
    @Autowired
    private WithDrawService withDrawService;
    @Autowired
    private BacklogItemPropertyRentBillRepository backlogItemPropertyRentBillRepository;
    @Autowired
    private BacklogItemPropertyOtherBillRepository backlogItemPropertyOtherBillRepository;
    @Autowired
    private BacklogItemHouseOtherBillRepository backlogItemHouseOtherBillRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private SaasBacklogItemBillRepository saasBacklogItemBillRepository;

    /**
     * App支付回调
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void appPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

        LOG.info("AliPayService appPayCallback<App支付回调>");
        AliPayCallback callBack = new AliPayCallback(null, null, request, response);
        Map<String, String> result = callBack.verifyResult();
        try {

            if (result == null) {
                callBack.resultFail();
                return;
            }

            /*String outTradeNo = result.get("passbackParams");
            if (StringUtils.isBlank(passbackParams)) {
                LOG.error("AliPayService appPayCallback<支付宝app支付回调> passbackParams is null");
                callBack.resultFail();
                return;
            }*/

            String outTradeNo = result.get("outTradeNo");
            LOG.info("AliPayService appPayCallback<支付宝app支付回调> outTradeNo={}", outTradeNo);
            PaymentVo paymentVo = redisService.getPaymentOrder(outTradeNo, PaymentVo.class);

            if (paymentVo == null) {
                LOG.error("AliPayService appPayCallback<支付宝app支付回调> 未找到预支付订单");
                callBack.resultSuccess();
                return;
            }

            if (paymentVo.getPaymentStatus() == 1) {
                LOG.info("AliPayService appPayCallback<支付宝app支付回调> 已支付成功");
                callBack.resultSuccess();
                return;
            }

            // 签名验证
            if (!callBack.verifySignature(paymentVo.getPublicKey())) {
                callBack.resultFail();
                return;
            }

            // tradeStatus=TRADE_SUCCESS(付款成功)
            // tradeStatus=TRADE_FINISHED(交易完成,无需处理，直接返回成功)
            // tradeStatus=TRADE_CLOSED(交易关闭,无需处理，直接返回成功)
            if (result.get("tradeStatus").equals("TRADE_FINISHED")
                    || result.get("tradeStatus").equals("TRADE_CLOSED")) {
                callBack.resultSuccess();
                return;
            }

            if (result.get("tradeStatus").equals("TRADE_SUCCESS")) {

                // 相关业务处理
                Integer totalAmount = DataUtils.doubleToInteger(Double.parseDouble(result.get("totalAmount")));

                Integer pAmount = DataUtils.doubleToInteger(paymentVo.getTotalAmount().doubleValue());
                if (totalAmount.intValue() != pAmount.intValue()) {
                    LOG.error("AliPayService appPayCallback<支付宝app支付回调> 支付金额不匹配 totalAmount={},cost={}",
                            DataUtils.IntegerToBigdecimal(totalAmount), DataUtils.IntegerToBigdecimal(pAmount));
                    callBack.resultSuccess();
                    return;
                }

                // 公租房费用管理-账单
                if (paymentVo.getBusinessType() == 1) {
                    handleBill(outTradeNo, result, totalAmount);
                } else if (paymentVo.getBusinessType() == 2) {
                    // 报修费用
                    handleRepairs(outTradeNo, result, totalAmount);
                } else if (paymentVo.getBusinessType() == 3) {
                    // 待办事项
                    handleBacklog(outTradeNo, result, totalAmount);
                } else if (paymentVo.getBusinessType() == 4) {
                    // 物业房产租金/押金
                    houseHandleBill(outTradeNo, result, totalAmount);
                } else if (paymentVo.getBusinessType() == 5) {
                    // 生活缴费
                    handleLifePay(outTradeNo, result, totalAmount);
                } else if (paymentVo.getBusinessType() == 6) {
                    // 公租房其它费用
                    otherHandleBill(outTradeNo, result, totalAmount);
                } else if (paymentVo.getBusinessType() == 7) {
                    // 物业房产其它费用
                    otherEstateHandleBill(outTradeNo, result, totalAmount);
                } else if (paymentVo.getBusinessType() == 8) {
                    // 一体机扫码支付
                    handleAioScanPay(outTradeNo, result, totalAmount);
                } else {
                    LOG.warn("WxPayService appPayCallback<微信app支付回调>, 未匹配支付业务类型, businessType={}, outTradeNo={}",
                            paymentVo.getBusinessType(), outTradeNo);
                }
            }
        } catch (Exception e) {
            LOG.error("App支付回异常" + e.getMessage(), e);
            callBack.resultFail();
        }
        callBack.resultSuccess();
    }

    /**
     * 费用管理-租金/押金账单明细
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void handleBill(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {

        LOG.info("AliPayService handleBill<支付宝app租金/押金账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<RentBill> bills = rentBillRepository.findByIdIn(redisVo.getIds());

        Date payTime = new Date();
        Integer billAmount = 0;

        HousePaymentOrder parment = housePaymentOrderRepository.findByOrderNumber(outTradeNo);
        if (parment != null && parment.getPayResult() == 1) {
            LOG.info("AliPayService appPayCallback<支付宝app支付回调> 以支付成功");
            return;
        }

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        for (RentBill b : bills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }

            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }

        rentBillRepository.saveAll(bills);
        housePaymentOrderRelationRepository.saveAll(porList);

        /**
         * 验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
         */
        // 根据当前支付的账单明细，找到缴费账单对应的所有合同
        List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
        Map<String, String> houseMap = new HashMap<>();
        List<String> contractNubmers = new ArrayList<>();
        for (RentBillRelation r : relationList) {
            houseMap.put(r.getContractNubmer(), r.getHouseId());
            contractNubmers.add(r.getContractNubmer());
        }
        contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
        // 查询拥有未支付的合同信息
        List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

        // 保存全部支付完成(租金 + 押金)的合同编号
        List<String> completedContracts = new ArrayList<>();
        // 保存全部支付完成的公租房id
        List<String> houseIds = new ArrayList<>();

        // 验证合同是否支付完成
        Map<String, String> map = noPayBillList.stream()
                .collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
        for (String contractNumber : contractNubmers) {
            String houseId = map.get(contractNumber);
            if (houseId == null) {
                completedContracts.add(contractNumber);
                String sHouseId = houseMap.get(contractNumber);
                if (StringUtils.isNotBlank(sHouseId)) {
                    houseIds.add(sHouseId);
                }
            }
        }

        // 更新公租房合同缴费状态
        if (!houseIds.isEmpty()) {
            List<House> houseList = houseRepository.findByIdIn(houseIds);
            houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
            houseRepository.saveAll(houseList);
        }

        // 更新"已确认待交租"的合同状态
        if (!completedContracts.isEmpty()) {
            List<Contract> contractList = contractRepository
                    .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
            contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
            contractRepository.saveAll(contractList);

            Date date = new Date();
            for (String contractNumber : completedContracts) {
                // 更新租金/押金待办事项状态
                List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                if (contractBill != null && contractBill.size() > 0) {
                    for (BacklogItemContractBill bill : contractBill) {
                        Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                        if (itemOpt.isPresent()) {
                            BacklogItem item = itemOpt.get();
                            item.setBusinessStatus("已缴费");
                            item.setHandleStatus(1);
                            item.setHandlerTime(date);
                            backlogItemRepository.save(item);
                        }
                    }

                }
                // 生成信息备案待提交待办事项
                Contract contract = contractRepository.findByContractNubmer(contractNumber);
                if (contract == null) {
                    LOG.error("WxPayService handleBill<支付宝app租金/押金账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                    return;
                }

                AppUser appUsers = null;
                if (StringUtils.isNotBlank(contract.getMatchUserId())) {
                    appUsers = appUserRepository.findByIdOrEnterpriseUserId(contract.getMatchUserId(), contract.getMatchUserId());
                }
                BacklogItem submitItem = new BacklogItem();
                submitItem.setHouseId(contract.getHouseId());
                submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                submitItem.setTitle("公租房信息备案待提交");
                submitItem.setBusinessStatus("待提交");
                submitItem.setHandleStatus(0);
                submitItem.setMatchUserId(contract.getMatchUserId());
                submitItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                submitItem.setCreateTime(new Date());
                BacklogItem save = backlogItemRepository.save(submitItem);

                BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                submit.setBacklogItemId(save.getId());
                submit.setMatchUserId(contract.getMatchUserId());
                backlogItemRecordSubmitRepository.save(submit);
            }
        }

        // 公租房租金待办事项
        rentBillBacklogItem(redisVo.getIds());

        // 更新支付记录
        HousePaymentOrder paymentOrder = new HousePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(2);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        housePaymentOrderRepository.save(paymentOrder);

        // 更新支付宝记录
        SaasHouseZfbPay zfb = new SaasHouseZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        saasHouseZfbPayRepository.save(zfb);

        // DepartmentHierarchy department
        // =departmentHierarchyRepository.findByOrgId(redisVo.getOrgId());

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        // 资金存储位置：1企业商户号 2平台商户号
        Integer storeType = 2;
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());

    }

    /**
     * 报修费用
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void handleRepairs(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {

        LOG.info("AliPayService handleRepairs<支付宝报修支付回调> outTradeNo={}", outTradeNo);
        RepairsPaymentRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, RepairsPaymentRedisVo.class);
        redisVo.setPaymentStatus(1);
        redisService.putPaymentRepairs(redisVo);
        Date payTime = new Date();

        Optional<EstateRepairsRecord> recordOpt = estateRepairsRecordRepository.findById(redisVo.getRepairsId());
        EstateRepairsRecord record = recordOpt.get();
        record.setStatus(RepairsStatusEnum.COMPLETED.getStatus());
        record.setPaymentTime(payTime);
        estateRepairsRecordRepository.save(record);

        // 更新支付记录

        RepairsPaymentOrder payment = new RepairsPaymentOrder();
        payment.setRepairsId(record.getId());
        payment.setOrderNumber(outTradeNo);
        payment.setPayResult(2);
        payment.setPayUserId(redisVo.getUserId());
        payment.setTotalAmount(totalAmount);
        payment.setPayTime(payTime);
        payment.setPayType(2);
        repairsPaymentOrderRepository.save(payment);

        // 更新支付宝记录
        SaasRepairsZfbPay zfb = new SaasRepairsZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        saasRepairsZfbPayRepository.save(zfb);

        // DepartmentHierarchy department
        // =departmentHierarchyRepository.findByOrgId(redisVo.getOrgId());

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, totalAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());

    }

    /**
     * 待办事项
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void handleBacklog(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {

        LOG.info("AliPayService handleBacklog<支付宝待办事项支付回调> outTradeNo={}", outTradeNo);
        BacklogItemRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, BacklogItemRedisVo.class);
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBacklog(redisVo);

        Optional<BacklogItem> itemOptional = backlogItemRepository.findById(redisVo.getId());
        Date payTime = new Date();
        BacklogItem logItem = itemOptional.get();
        logItem.setHandleStatus(1);
        logItem.setHandlerTime(payTime);
        backlogItemRepository.save(logItem);

        List<RentBill> bills = rentBillRepository.findByIdIn(redisVo.getIds());

        Integer billAmount = 0;

        HousePaymentOrder parment = housePaymentOrderRepository.findByOrderNumber(outTradeNo);

        if (parment != null && parment.getPayResult() == 1) {
            LOG.info("AliPayService appPayCallback<支付宝app待办事项回调> 已支付成功");
            return;
        }
        Integer chargeType = null;
        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        for (RentBill b : bills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            if (chargeType == null && b.getChargeType() == ChargeTypeEnum.RENT.getValue()) {
                chargeType = ChargeTypeEnum.RENT.getValue();
            }

            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            billAmount += b.getCost();
            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }

        rentBillRepository.saveAll(bills);
        housePaymentOrderRelationRepository.saveAll(porList);

        // 租金交钱，更新合同状态及房租状态
        /*
         * if (chargeType != null && chargeType ==
         * ChargeTypeEnum.RENT.getValue()) { // 账单合同房租关系 List<RentBillRelation>
         * relationList = rentBillRelationRepository
         * .findByRentBillIdIn(redisVo.getIds()); List<String> houseIds = new
         * ArrayList<>(); List<String> contractNubmers = new ArrayList<>();
         * relationList.forEach(r -> { houseIds.add(r.getHouseId());
         * contractNubmers.add(r.getContractNubmer()); });
         *
         * List<House> houseList = houseRepository.findByIdIn(houseIds);
         *
         * houseList.forEach(h -> h.setPaymentStatus(1));
         * houseRepository.saveAll(houseList);
         *
         * List<Contract> contractList =
         * contractRepository.findByContractNubmerIn(contractNubmers);
         *
         * contractList.forEach(c -> c.setStatus(7));
         *
         * contractRepository.saveAll(contractList); }
         */

        // 更新支付记录
        HousePaymentOrder paymentOrder = new HousePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(2);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        housePaymentOrderRepository.save(paymentOrder);

        // 更新支付宝记录
        SaasHouseZfbPay zfb = new SaasHouseZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        saasHouseZfbPayRepository.save(zfb);

        if (logItem.getType() == BacklogItemTypeEnum.RENT_BILL.getValue()) {
            // 押金/租金支付成功后，解冻智能锁
            List<SmartLock> lockList = smartLockRepository.findByHouseId(logItem.getHouseId());
            List<Long> lockIds = lockList.stream().map(SmartLock::getId).collect(Collectors.toList());

            // 查询账单id，解冻
            List<BacklogItemLock> blocks = backlogItemLockRepository.findByBacklogItemId(logItem.getId());
            List<Long> billIds = blocks.stream().map(BacklogItemLock::getBillId).collect(Collectors.toList());

            Map<String, List<Long>> map = new HashMap<>();
            map.put("lockIds", lockIds);
            map.put("billIds", billIds);
            smartLockCallBackService.backlogItemLock(map, "job-executor-thaw");
        }

        // DepartmentHierarchy department
        // =departmentHierarchyRepository.findByOrgId(redisVo.getOrgId());

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());
    }

    /**
     * 更新企业钱包
     *
     * @param orgId        产权ID
     * @param storeType    资金存储位置 1企业商户号 2平台商户号
     * @param bufferStatus 提现缓冲期生效状态
     * @param bufferDay    提现缓冲期天数
     * @param amount       金额
     * @param outTtadeNo   订单号
     * @param payTime      支付时间
     */
    public synchronized void updateWallet(Long orgId, Integer storeType, String bufferStatus, String bufferDay,
                                          Integer amount, String outTtadeNo, Date payTime, Integer type) {
        try {
            Wallet wallet = walletRepository.findByOrgIdAndStoreTypeAndType(orgId, storeType, type);

            if (wallet == null) {
                wallet = new Wallet();
                wallet.setOrgId(orgId);
                wallet.setStoreType(storeType);
                wallet.setBalanceAmount(0);
                wallet.setBufferAmount(0);
                wallet.setTotalAmount(0);
                wallet.setTotalWithdrawAmount(0);
                wallet.setUsableAmount(0);
                // 支付宝
                wallet.setType(type);
            }
            // 提现缓冲期生效
            if ("1".equals(bufferStatus)) {
                // 金额加入钱包缓冲期金额
                Integer bufferAmount = wallet.getBufferAmount() + amount;
                wallet.setBufferAmount(bufferAmount);
            } else {
                // 金额加入可提现金额
                Integer usableAmount = wallet.getUsableAmount() + amount;
                wallet.setUsableAmount(usableAmount);
            }

            // 注：
            // 钱包总余额 = 钱包可提现金额 + 钱包缓冲期金额
            // 累计收入 = 钱包总余额 + 累计提现金额
            // 累计提现金额 = 累计收入 - 钱包总余额

            // 钱包总余额
            Integer balanceAmount = wallet.getUsableAmount() + wallet.getBufferAmount();
            wallet.setBalanceAmount(balanceAmount);

            // 累计收入
            Integer totalAmount = wallet.getBalanceAmount() + wallet.getTotalWithdrawAmount();
            wallet.setTotalAmount(totalAmount);

            // 累计提现金额
            Integer totalWithdrawAmount = totalAmount - wallet.getBalanceAmount();

            wallet.setTotalWithdrawAmount(totalWithdrawAmount);
            wallet.setLastUpdateTime(new Date());
            walletRepository.save(wallet);
            // 提现缓冲期生效规则
            if ("1".equals(bufferStatus)) {

                WalletBuffer buffer = new WalletBuffer();
                buffer.setOrderNumber(outTtadeNo);
                buffer.setPayTime(payTime);
                buffer.setStatus(0);
                buffer.setTotalAmount(amount);
                buffer.setWalletId(wallet.getId());
                Date endTime = DateUtils.getAddDaysTime(new Date(), Integer.valueOf(bufferDay));
                buffer.setBufferEndTime(endTime);
                walletBufferRepository.save(buffer);
            }
        } catch (Exception e) {
            LOG.error("更新企业钱包异常" + e.getMessage(), e);
        }
    }

    /**
     * 物业房产-租金/押金
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void houseHandleBill(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {

        LOG.info("AliPayService houseHandleBill<支付宝app物业房产租金/押金账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<EstateRentBill> bills = estateRentBillRepository.findByIdIn(redisVo.getIds());

        Date payTime = new Date();
        Integer billAmount = 0;

        EstatePaymentOrder parment = estatePaymentOrderRepository.findByOrderNumber(outTradeNo);
        if (parment != null && parment.getPayResult() == 1) {
            LOG.info("AliPayService houseHandleBill<支付宝app物业房产支付回调> 以支付成功");
            return;
        }

        List<EstatePaymentOrderRelation> porList = new ArrayList<>();
        for (EstateRentBill b : bills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }

            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }

        // 更新租金/押金账单明细支付状态
        estateRentBillRepository.saveAll(bills);
        // 新增账单与支付关系明细
        estatePaymentOrderRelationRepository.saveAll(porList);

        // 修改待办事项的状态
        propertyRentItem(redisVo.getIds());

        // 新增账单支付记录
        EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(2);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        estatePaymentOrderRepository.save(paymentOrder);

        // 新增支付宝支付明细
        EstateZfbPay zfb = new EstateZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        estateZfbPayRepository.save(zfb);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        // 资金存储位置：1企业商户号 2平台商户号
        Integer storeType = 2;
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());

    }

    /**
     * -----
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void handleRepairss(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {

        LOG.info("AliPayService handleRepairs<支付宝报修支付回调> outTradeNo={}", outTradeNo);
        RepairsPaymentRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, RepairsPaymentRedisVo.class);
        redisVo.setPaymentStatus(1);
        redisService.putPaymentRepairs(redisVo);

        Optional<EstateRepairsRecord> recordOpt = estateRepairsRecordRepository.findById(redisVo.getRepairsId());
        EstateRepairsRecord record = recordOpt.get();
        record.setStatus(RepairsStatusEnum.COMPLETED.getStatus());
        estateRepairsRecordRepository.save(record);

        // 更新支付记录
        Date payTime = new Date();
        RepairsPaymentOrder payment = new RepairsPaymentOrder();
        payment.setRepairsId(record.getId());
        payment.setOrderNumber(outTradeNo);
        payment.setPayResult(2);
        payment.setPayUserId(redisVo.getUserId());
        payment.setTotalAmount(totalAmount);
        payment.setPayTime(payTime);
        payment.setPayType(2);
        repairsPaymentOrderRepository.save(payment);

        // 更新支付宝记录
        SaasRepairsZfbPay zfb = new SaasRepairsZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        saasRepairsZfbPayRepository.save(zfb);

        // DepartmentHierarchy department
        // =departmentHierarchyRepository.findByOrgId(redisVo.getOrgId());

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, totalAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());

    }

    /**
     * 费用管理-公租房其它费用账单
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     * @author shun
     * @date 2021年7月12日
     */
    public void otherHandleBill(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {
        LOG.info("AliPayService otherHandleBill<支付宝app公租房其它费用账单账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("AliPayService otherHandleBill<支付宝app公租房其它费用账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<ExpenseBill> expenseBills = expenseBillRepository.findByIdIn(redisVo.getIds());
        if (CollectionUtils.isEmpty(expenseBills)) {
            LOG.error("AliPayService otherHandleBill<支付宝app公租房其它费用账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }
        LOG.info("AliPayService otherHandleBill, redisVo={}, expenseBills={}", JSON.toJSONString(redisVo),
                JSON.toJSONString(expenseBills));

        Date payTime = new Date();
        Integer billAmount = 0;

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        for (ExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            // 账单与支付记录关系表
            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }

        // 更新账单明细支付状态
        expenseBillRepository.saveAll(expenseBills);
        housePaymentOrderRelationRepository.saveAll(porList);

        // 公租房其他费用待办事项
        houseOtherBillItem(redisVo.getIds());

        // 新增账单支付记录
        HousePaymentOrder paymentOrder = new HousePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(2);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        housePaymentOrderRepository.save(paymentOrder);

        // 新增支付宝支付明细
        EstateZfbPay zfb = new EstateZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        estateZfbPayRepository.save(zfb);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());
    }

    /**
     * 费用管理-物业房产其它费用账单
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     * @author shun
     * @date 2021年7月12日
     */
    public void otherEstateHandleBill(String outTradeNo, Map<String, String> result, Integer totalAmount)
            throws Exception {
        LOG.info("AliPayService otherEstateHandleBill<支付宝app物业房产其它费用账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("AliPayService otherEstateHandleBill<支付宝app物业房产其它费用支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<EstateExpenseBill> expenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getIds());
        if (CollectionUtils.isEmpty(expenseBills)) {
            LOG.error("AliPayService otherEstateHandleBill<支付宝app物业房产其它费用支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }
        LOG.info("AliPayService otherEstateHandleBill, redisVo={}, expenseBills={}", JSON.toJSONString(redisVo),
                JSON.toJSONString(expenseBills));

        Date payTime = new Date();
        Integer billAmount = 0;

        List<EstatePaymentOrderRelation> porList = new ArrayList<>();
        for (EstateExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            // 账单与支付记录关系表
            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());// 退租
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }

        // 更新账单明细支付状态
        estateExpenseBillRepository.saveAll(expenseBills);
        estatePaymentOrderRelationRepository.saveAll(porList);


        // 物业其他费用待办事项
        propertyOtherItem(redisVo.getIds());

        // 新增账单支付记录
        EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(2);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        estatePaymentOrderRepository.save(paymentOrder);

        // 新增支付宝支付明细
        EstateZfbPay zfb = new EstateZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        estateZfbPayRepository.save(zfb);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());
    }

    /**
     * 生活缴费
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     */
    /*public void handleLifePay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("AliPayService handleLifePay<微信app生活缴费账单账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("AliPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        Date payTime = new Date();
        Integer billAmount = 0;

        if (redisVo.getType() == 1) {
            List<RentBill> rentBills = new ArrayList<>();
            List<ExpenseBill> expenseBills = new ArrayList<>();
            if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
            }
            if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
                expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            }

            if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)) {
                LOG.error("AliPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
                return;
            }

            LOG.info("AliPayService handleLifePay, redisVo={}, rentBills={}, expenseBills={}", JSON.toJSONString(redisVo), JSON.toJSONString(rentBills),
                    JSON.toJSONString(expenseBills));

            List<HousePaymentOrderRelation> porList = new ArrayList<>();
            for (RentBill b : rentBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                }
                porList.add(por);
            }
            rentBillRepository.saveAll(rentBills);

            for (ExpenseBill b : expenseBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                // 其它费用类型转换
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                } else if (b.getChargeType() == 3) {
                    por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                } else if (b.getChargeType() == 4) {
                    por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                } else if (b.getChargeType() == 5) {
                    por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                } else if (b.getChargeType() == 6) {
                    por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                } else if (b.getChargeType() == 7) {
                    por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                }
                porList.add(por);
            }
            expenseBillRepository.saveAll(expenseBills);

            housePaymentOrderRelationRepository.saveAll(porList);

            //验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
            if (!CollectionUtils.isEmpty(redisVo.getIds())){
                // 根据当前支付的账单明细，找到缴费账单对应的所有合同
                List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
                Map<String, String> houseMap = new HashMap<>();
                List<String> contractNubmers = new ArrayList<>();
                for (RentBillRelation r : relationList) {
                    houseMap.put(r.getContractNubmer(), r.getHouseId());
                    contractNubmers.add(r.getContractNubmer());
                }
                contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
                // 查询拥有未支付的合同信息
                List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

                // 保存全部支付完成(租金 + 押金)的合同编号
                List<String> completedContracts = new ArrayList<>();
                // 保存全部支付完成的公租房id
                List<String> houseIds = new ArrayList<>();

                // 验证合同是否支付完成
                Map<String, String> map = noPayBillList.stream()
                        .collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
                for (String contractNumber : contractNubmers) {
                    String houseId = map.get(contractNumber);
                    if (houseId == null) {
                        completedContracts.add(contractNumber);
                        String sHouseId = houseMap.get(contractNumber);
                        if (StringUtils.isNotBlank(sHouseId)) {
                            houseIds.add(sHouseId);
                        }
                    }
                }

                // 更新公租房合同缴费状态
                if (!houseIds.isEmpty()) {
                    List<House> houseList = houseRepository.findByIdIn(houseIds);
                    houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                    houseRepository.saveAll(houseList);
                }

                // 更新"已确认待交租"的合同状态
                if (!completedContracts.isEmpty()) {
                    List<Contract> contractList = contractRepository
                            .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                    contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                    contractRepository.saveAll(contractList);

                    Date date = new Date();
                    for (String contractNumber : completedContracts) {
                        //更新租金/押金待办事项状态
                        BacklogItemContractBill contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                        if (contractBill != null) {
                            Optional<BacklogItem> itemOpt = backlogItemRepository.findById(contractBill.getBacklogItemId());
                            if (itemOpt.isPresent()) {
                                BacklogItem item = itemOpt.get();
                                item.setBusinessStatus("已缴费");
                                item.setHandleStatus(1);
                                item.setHandlerTime(date);
                                backlogItemRepository.save(item);
                            }
                        }
                        //生成信息备案待提交待办事项
                        Contract contract = contractRepository.findByContractNubmer(contractNumber);
                        if (contract == null) {
                            LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                            return;
                        }
                        BacklogItem submitItem = new BacklogItem();
                        submitItem.setHouseId(contract.getHouseId());
                        submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                        submitItem.setTitle("公租房信息备案待提交");
                        submitItem.setBusinessStatus("待提交");
                        submitItem.setHandleStatus(0);
                        submitItem.setMatchUserId(contract.getMatchUserId());
                        submitItem.setCreateTime(new Date());
                        BacklogItem save = backlogItemRepository.save(submitItem);

                        BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                        submit.setBacklogItemId(save.getId());
                        submit.setMatchUserId(contract.getMatchUserId());
                        backlogItemRecordSubmitRepository.save(submit);
                    }
                }
            }

            HousePaymentOrder paymentOrder = new HousePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            housePaymentOrderRepository.save(paymentOrder);
        }

        if (redisVo.getType() == 2) {
            List<EstateRentBill> estateRentBills = new ArrayList<>();
            List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
            if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getIds());
            }
            if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
                estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            }

            if (CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
                LOG.error("AliPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
                return;
            }

            LOG.info("AliPayService handleLifePay, redisVo={}, estateRentBills={}, estateExpenseBills={}", JSON.toJSONString(redisVo), JSON.toJSONString(estateRentBills),
                    JSON.toJSONString(estateExpenseBills));

            List<EstatePaymentOrderRelation> porList = new ArrayList<>();
            for (EstateRentBill b : estateRentBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                }
                porList.add(por);
            }
            estateRentBillRepository.saveAll(estateRentBills);

            for (EstateExpenseBill b : estateExpenseBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                // 其它费用类型转换
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                } else if (b.getChargeType() == 3) {
                    por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                } else if (b.getChargeType() == 4) {
                    por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                } else if (b.getChargeType() == 5) {
                    por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                } else if (b.getChargeType() == 6) {
                    por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                } else if (b.getChargeType() == 7) {
                    por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                }
                porList.add(por);
            }
            estateExpenseBillRepository.saveAll(estateExpenseBills);

            estatePaymentOrderRelationRepository.saveAll(porList);

            EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            estatePaymentOrderRepository.save(paymentOrder);
        }

        // 新增支付宝支付明细
        EstateZfbPay zfb = new EstateZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        estateZfbPayRepository.save(zfb);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());
    }*/
    public void handleLifePay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("AliPayService handleLifePay<微信app生活缴费账单账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("AliPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        Date payTime = new Date();
        Integer billAmount = 0;

        // 公租房-租金/押金账单明细
        List<RentBill> rentBills = new ArrayList<>();
        // 公租房-其它费用账单明细
        List<ExpenseBill> expenseBills = new ArrayList<>();
        // 物业房产-租金/押金账单明细
        List<EstateRentBill> estateRentBills = new ArrayList<>();
        // 物业房产-其它费用账单明细
        List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
            // 公租房租金押金账单
            rentBillBacklogItem(redisVo.getIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
            expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            // 公租房其他费用
            houseOtherBillItem(redisVo.getExpenseIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateRentIds())) {
            estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getEstateRentIds());
            // 物业房租金押金账单
            propertyRentItem(redisVo.getEstateRentIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateExpenseIds())) {
            estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getEstateExpenseIds());
            // 物业其他费用
            propertyOtherItem(redisVo.getEstateExpenseIds());
        }

        if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)
                && CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
            LOG.error("AliPayService handleAioScanPay<支付宝生活缴费账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }

        LOG.info("AliPayService handleAioScanPay<支付宝生活缴费账单支付回调>, redisVo={}", JSON.toJSONString(redisVo));

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        List<EstatePaymentOrderRelation> porList2 = new ArrayList<>();
        for (RentBill b : rentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }
        rentBillRepository.saveAll(rentBills);

        for (ExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }
        expenseBillRepository.saveAll(expenseBills);

        for (EstateRentBill b : estateRentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList2.add(por);
        }
        estateRentBillRepository.saveAll(estateRentBills);

        for (EstateExpenseBill b : estateExpenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList2.add(por);
        }
        estateExpenseBillRepository.saveAll(estateExpenseBills);

        housePaymentOrderRelationRepository.saveAll(porList);
        estatePaymentOrderRelationRepository.saveAll(porList2);

        // 验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            // 根据当前支付的账单明细，找到缴费账单对应的所有合同
            List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
            Map<String, String> houseMap = new HashMap<>();
            List<String> contractNubmers = new ArrayList<>();
            for (RentBillRelation r : relationList) {
                houseMap.put(r.getContractNubmer(), r.getHouseId());
                contractNubmers.add(r.getContractNubmer());
            }
            contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
            // 查询拥有未支付的合同信息
            List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

            // 保存全部支付完成(租金 + 押金)的合同编号
            List<String> completedContracts = new ArrayList<>();
            // 保存全部支付完成的公租房id
            List<String> houseIds = new ArrayList<>();

            // 验证合同是否支付完成
            Map<String, String> map = noPayBillList.stream().collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
            for (String contractNumber : contractNubmers) {
                String houseId = map.get(contractNumber);
                if (houseId == null) {
                    completedContracts.add(contractNumber);
                    String sHouseId = houseMap.get(contractNumber);
                    if (StringUtils.isNotBlank(sHouseId)) {
                        houseIds.add(sHouseId);
                    }
                }
            }

            // 更新公租房合同缴费状态
            if (!houseIds.isEmpty()) {
                List<House> houseList = houseRepository.findByIdIn(houseIds);
                houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                houseRepository.saveAll(houseList);
            }

            // 更新"已确认待交租"的合同状态
            if (!completedContracts.isEmpty()) {
                List<Contract> contractList = contractRepository
                        .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                contractRepository.saveAll(contractList);

                Date date = new Date();
                for (String contractNumber : completedContracts) {
                    // 更新租金/押金待办事项状态
                    List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                    if (contractBill != null && contractBill.size() > 0) {
                        for (BacklogItemContractBill bill : contractBill) {
                            Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                            if (itemOpt.isPresent()) {
                                BacklogItem item = itemOpt.get();
                                item.setBusinessStatus("已缴费");
                                item.setHandleStatus(1);
                                item.setHandlerTime(date);
                                backlogItemRepository.save(item);
                            }
                        }

                    }
                    // 生成信息备案待提交待办事项
                    Contract contract = contractRepository.findByContractNubmer(contractNumber);
                    if (contract == null) {
                        LOG.error("WxPayService handleAioScanPay<支付宝一体机扫码账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                        return;
                    }

                    AppUser appUsers = null;
                    if (StringUtils.isNotBlank(contract.getMatchUserId())) {
                        appUsers = appUserRepository.findByIdOrEnterpriseUserId(contract.getMatchUserId(), contract.getMatchUserId());
                    }

                    BacklogItem submitItem = new BacklogItem();
                    submitItem.setHouseId(contract.getHouseId());
                    submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                    submitItem.setTitle("公租房信息备案待提交");
                    submitItem.setBusinessStatus("待提交");
                    submitItem.setHandleStatus(0);
                    submitItem.setMatchUserId(contract.getMatchUserId());
                    submitItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                    submitItem.setCreateTime(new Date());
                    BacklogItem save = backlogItemRepository.save(submitItem);

                    BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                    submit.setBacklogItemId(save.getId());
                    submit.setMatchUserId(contract.getMatchUserId());
                    backlogItemRecordSubmitRepository.save(submit);
                }
            }
        }

        if (!CollectionUtils.isEmpty(rentBills) || !CollectionUtils.isEmpty(expenseBills)) {
            HousePaymentOrder paymentOrder = new HousePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            housePaymentOrderRepository.save(paymentOrder);
        }

        if (!CollectionUtils.isEmpty(estateRentBills) || !CollectionUtils.isEmpty(estateExpenseBills)) {
            EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            estatePaymentOrderRepository.save(paymentOrder);
        }

        // 新增支付宝支付明细
        EstateZfbPay zfb = new EstateZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        estateZfbPayRepository.save(zfb);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());
    }

    /**
     * 一体机扫码支付
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     */
    public void handleAioScanPay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("AliPayService handleAioScanPay<支付宝一体机扫码账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("AliPayService handleAioScanPay<支付宝一体机扫码账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        Date payTime = new Date();
        Integer billAmount = 0;

        List<RentBill> rentBills = new ArrayList<>();
        List<ExpenseBill> expenseBills = new ArrayList<>();
        List<EstateRentBill> estateRentBills = new ArrayList<>();
        List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
            // 公租房租金押金账单
            rentBillBacklogItem(redisVo.getIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
            expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            // 公租房其他费用
            houseOtherBillItem(redisVo.getExpenseIds());

        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateRentIds())) {
            estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getEstateRentIds());
            // 物业房租金押金账单
            propertyRentItem(redisVo.getEstateRentIds());

        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateExpenseIds())) {
            estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getEstateExpenseIds());
            // 物业其他费用
            propertyOtherItem(redisVo.getEstateExpenseIds());
        }

        if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)
                && CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
            LOG.error("AliPayService handleAioScanPay<支付宝一体机扫码账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }

        LOG.info("AliPayService handleAioScanPay<支付宝一体机扫码账单支付回调>, redisVo={}", JSON.toJSONString(redisVo));

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        List<EstatePaymentOrderRelation> porList2 = new ArrayList<>();
        for (RentBill b : rentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }
        rentBillRepository.saveAll(rentBills);

        for (ExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }
        expenseBillRepository.saveAll(expenseBills);

        for (EstateRentBill b : estateRentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList2.add(por);
        }
        estateRentBillRepository.saveAll(estateRentBills);

        for (EstateExpenseBill b : estateExpenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(2);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList2.add(por);
        }
        estateExpenseBillRepository.saveAll(estateExpenseBills);

        housePaymentOrderRelationRepository.saveAll(porList);
        estatePaymentOrderRelationRepository.saveAll(porList2);

        // 验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            // 根据当前支付的账单明细，找到缴费账单对应的所有合同
            List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
            Map<String, String> houseMap = new HashMap<>();
            List<String> contractNubmers = new ArrayList<>();
            for (RentBillRelation r : relationList) {
                houseMap.put(r.getContractNubmer(), r.getHouseId());
                contractNubmers.add(r.getContractNubmer());
            }
            contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
            // 查询拥有未支付的合同信息
            List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

            // 保存全部支付完成(租金 + 押金)的合同编号
            List<String> completedContracts = new ArrayList<>();
            // 保存全部支付完成的公租房id
            List<String> houseIds = new ArrayList<>();

            // 验证合同是否支付完成
            Map<String, String> map = noPayBillList.stream().collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
            for (String contractNumber : contractNubmers) {
                String houseId = map.get(contractNumber);
                if (houseId == null) {
                    completedContracts.add(contractNumber);
                    String sHouseId = houseMap.get(contractNumber);
                    if (StringUtils.isNotBlank(sHouseId)) {
                        houseIds.add(sHouseId);
                    }
                }
            }

            // 更新公租房合同缴费状态
            if (!houseIds.isEmpty()) {
                List<House> houseList = houseRepository.findByIdIn(houseIds);
                houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                houseRepository.saveAll(houseList);
            }

            // 更新"已确认待交租"的合同状态
            if (!completedContracts.isEmpty()) {
                List<Contract> contractList = contractRepository
                        .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                contractRepository.saveAll(contractList);

                Date date = new Date();
                for (String contractNumber : completedContracts) {
                    // 更新租金/押金待办事项状态
                    List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                    if (contractBill != null && contractBill.size() > 0) {
                        for (BacklogItemContractBill bill : contractBill) {
                            Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                            if (itemOpt.isPresent()) {
                                BacklogItem item = itemOpt.get();
                                item.setBusinessStatus("已缴费");
                                item.setHandleStatus(1);
                                item.setHandlerTime(date);
                                backlogItemRepository.save(item);
                            }
                        }

                    }
                    // 生成信息备案待提交待办事项
                    Contract contract = contractRepository.findByContractNubmer(contractNumber);
                    if (contract == null) {
                        LOG.error("WxPayService handleAioScanPay<支付宝一体机扫码账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                        return;
                    }

                    AppUser appUsers = null;
                    if (StringUtils.isNotBlank(contract.getMatchUserId())) {
                        appUsers = appUserRepository.findByIdOrEnterpriseUserId(contract.getMatchUserId(), contract.getMatchUserId());
                    }
                    BacklogItem submitItem = new BacklogItem();
                    submitItem.setHouseId(contract.getHouseId());
                    submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                    submitItem.setTitle("公租房信息备案待提交");
                    submitItem.setBusinessStatus("待提交");
                    submitItem.setHandleStatus(0);
                    submitItem.setMatchUserId(contract.getMatchUserId());
                    submitItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                    submitItem.setCreateTime(new Date());
                    BacklogItem save = backlogItemRepository.save(submitItem);

                    BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                    submit.setBacklogItemId(save.getId());
                    submit.setMatchUserId(contract.getMatchUserId());
                    backlogItemRecordSubmitRepository.save(submit);
                }
            }
        }

        if (!CollectionUtils.isEmpty(rentBills) || !CollectionUtils.isEmpty(expenseBills)) {
            HousePaymentOrder paymentOrder = new HousePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            housePaymentOrderRepository.save(paymentOrder);
        }

        if (!CollectionUtils.isEmpty(estateRentBills) || !CollectionUtils.isEmpty(estateExpenseBills)) {
            EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            estatePaymentOrderRepository.save(paymentOrder);
        }

        // 新增支付宝支付明细
        EstateZfbPay zfb = new EstateZfbPay();
        zfb.setOutTradeNo(result.get("outTradeNo"));
        zfb.setOrderNumber(result.get("outTradeNo"));
        zfb.setAppid(result.get("appid"));
        zfb.setTradeNo(result.get("trade_no"));
        zfb.setCallbackTime(DateUtils.convert(result.get("notifyTime"), DateUtils.FORMAT_DATETIME_14));
        zfb.setCreateTime(new Date());
        zfb.setPayAmount(totalAmount);
        zfb.setPayStatus(1);
        zfb.setPayTradeStatus(result.get("tradeStatus"));
        zfb.setSellerId(result.get("sellerId"));
        zfb.setAliUserId(result.get("buyerId"));
        estateZfbPayRepository.save(zfb);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo, payTime,
                PaymentTypeEnum.ALI.getValue());
    }

    /**
     * 公租房租金待办事项
     *
     * @param ids
     */
    public void rentBillBacklogItem(List<Long> ids) {

        List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByRentBillIdInAndDepositBillIdIn(ids, ids);
        if (contractBill != null && contractBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemContractBill bill : contractBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }

    /**
     * 公租房其他费用账单待办事项
     *
     * @param ids
     */
    public void houseOtherBillItem(List<Long> ids) {
        List<BacklogItemHouseOtherBill> houseOtherBill = backlogItemHouseOtherBillRepository.findByBillIdIn(ids);

        if (houseOtherBill != null && houseOtherBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemHouseOtherBill bill : houseOtherBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }

    /**
     * 非公租房租金待办事项
     *
     * @param ids
     */
    public void propertyRentItem(List<Long> ids) {
        List<BacklogItemPropertyRentBill> propertyRentBill = backlogItemPropertyRentBillRepository.findByRentBillIdInOrDepositBillIdIn(ids, ids);
        if (propertyRentBill != null && propertyRentBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemPropertyRentBill bill : propertyRentBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }


    /**
     * 非公租房其他账单待办事项
     *
     * @param ids
     */
    public void propertyOtherItem(List<Long> ids) {
        List<BacklogItemPropertyOtherBill> propertyOtherBill = backlogItemPropertyOtherBillRepository.findByBillIdIn(ids);
        if (propertyOtherBill != null && propertyOtherBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemPropertyOtherBill bill : propertyOtherBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }

        List<SaasBacklogItemBill> saasBacklogItemBillList = saasBacklogItemBillRepository.findByBillId(ids);
        if (saasBacklogItemBillList != null && saasBacklogItemBillList.size() > 0) {
            Date date = new Date();
            for (SaasBacklogItemBill bill : saasBacklogItemBillList) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }


}
